package com.example.its2021606134chh.BusModule;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class BusActivity extends AppCompatActivity {
    private String[] allList = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"};
    private List<rvBusData> list = new ArrayList<>();
    private Timer timer;
    private TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bus);
        Button btnBusCancel = (Button) findViewById(R.id.btnBusCancel);
        RecyclerView rvBusList = (RecyclerView) findViewById(R.id.rvDiaBusList);
        rvBusList.setLayoutManager(new LinearLayoutManager(BusActivity.this));
        btnBusCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                list.clear();
                for (String s : allList) {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
                            Gson gson = new Gson();
                            Bus bus = gson.fromJson(json, Bus.class);
                            Log.i("TAG", String.valueOf(bus.getBusCapacity()));
                            list.add(new rvBusData(Integer.parseInt(s), bus.getBusCapacity()));
                            rvBusList.setAdapter(new BusRViewAdapter(list));
                        }
                    }, "get_bus_capacity", new String[]{"BusId", "UserName"}, s, "user1");
                }
            }
        };
        timer.schedule(timerTask, 0, 10000);
    }
    @Override
    public void onDestroy() {
        Log.i("TAG", "onDestroy");
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask =  null;
        }
        super.onDestroy();
    }
}